package com.weds.edwx.job;

import com.alibaba.fastjson.JSONObject;
import com.weds.core.utils.coder.Coder;
import com.weds.edwx.constant.LeCaiParams;
import com.weds.edwx.entity.*;
import com.weds.edwx.service.LeCaiDepUserService;
import com.weds.edwx.util.TimeUtil;
import com.weds.etl.base.SchedulerJob;
import com.weds.web.comm.entity.CommProcEntity;
import com.weds.web.comm.service.CommProcService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.JobExecutionContext;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

public class LeCaiUserSchedulerJob extends SchedulerJob {

    private Logger log = LogManager.getLogger();

    @Resource
    private LeCaiParams leCaiParams;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private CommProcService commProcService;

    @Resource
    private LeCaiDepUserService leCaiDepUserService;

    @Override
    @Transactional
    public void execute(JobExecutionContext context) {
        boolean flag = true;
        int start = 0;
        //时间戳
        String stamp=TimeUtil.getNowTimeStamp();
        //签名
        String sign="";
             if(leCaiParams.getDomain().equals("")){
                 sign=Coder.md5Hex(stamp+""+leCaiParams.getKey());
             }else{
                 sign=Coder.md5Hex(leCaiParams.getDomain()+""+stamp+""+leCaiParams.getKey());
             }
        //用户ID
        String companyId=leCaiParams.getCompanyId();
        //如果人员列表有值
        //if(resultContent.size()>0){
            //删除tmp_dt_user表
            leCaiDepUserService.deleteTmpDtUser();
        //}
        //============================================================================
        while (flag) {
            flag = false;
            //======组织参数============================================
            LeCaiUserEntity lcue = new LeCaiUserEntity();
            lcue.setCompanyId(companyId);
            lcue.setStamp(stamp);
            lcue.setSign(sign);
            lcue.setPageIndex(start);
            lcue.setPageSize(leCaiParams.getRow());
            //======发送请求============================================
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> request = new HttpEntity<>(JSONObject.toJSONString(lcue), headers);
            String resp = restTemplate.postForObject(leCaiParams.getUserUrl(), request, String.class);
            LeCaiUserResp lcResp = JSONObject.parseObject(resp, LeCaiUserResp.class);
            //======处理响应结果============================================
            //请求超时
            if(lcResp.getStatus().equals(1)) {
                stamp=TimeUtil.getNowTimeStamp();
                lcue.setStamp(stamp);
                request = new HttpEntity<>(JSONObject.toJSONString(lcue), headers);
                resp = restTemplate.postForObject(leCaiParams.getUserUrl(), request, String.class);
                lcResp = JSONObject.parseObject(resp, LeCaiUserResp.class);
            }
            //======================================================================================
            //请求成功
            if (lcResp.getStatus().equals(0)) {
                //条数 数量
                int count = lcResp.getCount();
                List<UserResultContent> resultContent = lcResp.getResultContent();
                System.out.println("从乐才取得的员工数量=="+resultContent.size());
                if (count > 0 && resultContent.size() > 0) {
                    ///如果取回来的记录是100条，与设置的每页取100条相等，那么就说明还没有取到最后一页，还得继续取
                    if (resultContent.size() == leCaiParams.getRow()) {
                        start = start + 1;
                        flag = true;
                    }
                    List<TmpDtUserReq> dataList = new ArrayList<>();
                    ///每次取100条，循环100条
                    for (int i = 0; i < resultContent.size(); i++) {
                        UserResultContent urlc=resultContent.get(i);
                            //插入tmp_dt_user表入参类
                            TmpDtUserReq tmpDtUserReq = new TmpDtUserReq();
                            //主键
                            tmpDtUserReq.setZh(urlc.getEmpID().toString());
                            //工号
                            tmpDtUserReq.setUserNo(urlc.getCode());
                            //姓名
                            tmpDtUserReq.setUserLname(urlc.getName());
                            //同步人员时部门编号用对方的部门id
                            tmpDtUserReq.setDepNo(urlc.getDepartID().toString());
                            //手机号码
                            tmpDtUserReq.setUserTelephone(urlc.getMobile());
                            //民族
                            tmpDtUserReq.setUserNation(urlc.getNation());
                            //学历
                            tmpDtUserReq.setUserXueli(urlc.getEdulevel());
                            //职务
                            tmpDtUserReq.setUserDuty(urlc.getPostName());
                            //在职离职
                            tmpDtUserReq.setUserType(urlc.getIsOnDuty()==1?0:51);
                            //性别
                            tmpDtUserReq.setUserSex(urlc.getGender());
                        dataList.add(tmpDtUserReq);
                        ///每10个人插入表中一次，或者循环到了最后一个插入
                        if (dataList.size() == 10 || i == resultContent.size() - 1) {
                            leCaiDepUserService.insertBatch(dataList);
                            dataList.clear();
                        }
                    }
                }
            } else {
                System.out.println("同步人员返回错误信息：" + lcResp.getMsg());
            }
        }
        //调用同步部门的存储过程
        CommProcEntity commProcEntity = new CommProcEntity();
        commProcEntity.setProcName("updateuser_big_scm2");
        commProcService.loadProcData(commProcEntity);
        //============================================================================
    }







}
